<template>
  <el-form v-model="api">
    <el-form-item label="api地址">
      <el-input v-model="api.url"></el-input>
      {{urlResult}}
    </el-form-item>
    <el-form-item label="请求方式">
      <el-select v-model="api.method">
        <el-option label="Get" value="get"></el-option>
        <el-option label="Post" value="post"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="Body">
      <el-input type="textarea" v-model="api.body"></el-input>
      {{bodyResult}}
    </el-form-item>
    <el-form-item label="测试对象">
      <el-input type="textarea" v-model="api.testObj"></el-input>
    </el-form-item>
    <el-button @click="click()">测试</el-button>
  </el-form>
</template>

<script>
export default {
  methods:{
    click(){
      let obj=JSON.parse(this.api.testObj)      
      let resultUrl=this.parseUrl(this.api.url,obj)
      this.urlResult=resultUrl
      let resultbody=this.parseBody(this.api.body,obj)
      this.bodyResult=resultbody
    },
    parseUrl(url,obj){
      let pa=/\{(.+?)\}/gm
      let match=url.match(pa)      
      match.forEach(m => {        
        let sig=m.replace("{","").replace("}","")        
        let arr=sig.split(".")
        let root=obj
        arr.forEach(x=>{
          root=root[x]
        })        
        url=url.replace(m,root)
      });      
      return url
    },
    parseBody(body,obj){
      let pa=/{[^{}]+?}/gm
      let match=body.match(pa)
      match.forEach(m => {                
        let sig=m.replace("{","").replace("}","")        
        let arr=sig.split(".")        
        let root=obj
        arr.forEach(x=>{
          root=root[x]
        })
        let value=root        
        if(typeof(value)=="string") value='"'+value+'"'
        body=body.replace(m,value)
      });
      return body
    }
  },
  data(){
    return {
      urlResult:"",
      bodyResult:"",
      api:{
        url:"http://abc.com/{int}/{child.a}",
        method:"get",
        body:'{"id":{int},"title":{str},"bool":{bool},"child":{child.b}}',
        // body:'{"list":[{"id":{int}},{"id":{child.a}}]}',
        testObj:'{"int":1,"str":"abc","bool":false,"child":{"a":123,"b":"bbb"}}'
      }
    }
  }
}
</script>

<style>

</style>